const HtmlPlugin = require("html-webpack-plugin");
const OpenBrowser = require("open-browser-webpack-plugin");
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebPlugin = require('copy-webpack-plugin');

const {
    htmlPlugin,providePlugin,
    openBrowser,proxyList,
    copyPlugin} = require("../conf/index");
const plugins = [];
const proxys = {};

/**
 * @function init               初始化
 * @function clearDev           清除dev文件夹      
 * @function dealHtmlPlugin     处理html
 * @function dealProvidePlugin  将jquery全局化   
 * @function dealOpenBrowser    打开浏览器
 * @function extractText        分离css,不放在html,单独成为一个文件
 */
function init(){
    clearDev();
    dealHtmlPlugin();
    dealProvidePlugin();
    dealOpenBrowser();
    extractText();
    gpProxy();
    dealCopyPlugin();
}

function clearDev(){
    plugins.push(new CleanWebpackPlugin());
}

function dealHtmlPlugin(){
    for(let i = 0, item; item = htmlPlugin[i++];){
        plugins.push(
            new HtmlPlugin({
            filename : item.filename,
            template : item.template,
            chunks: item.chunks || [],
            inject: true
        })
      )
    }
}

function dealProvidePlugin(){
    for(let i = 0, item; item = providePlugin[i++];){
        plugins.push(
            new webpack.ProvidePlugin(item)
        );
    }
}

function dealOpenBrowser(){
    plugins.push(
        new OpenBrowser(openBrowser)
    );
}

function extractText(){
    plugins.push(
        new ExtractTextPlugin({
            filename:  (getPath) => {
            return getPath('scss/[name].css').replace('scss/scripts', 'scss');
            },
            allChunks: true
      })
    );
}

function gpProxy(){
    for(let attr in proxyList) {
        let options = {
            target : proxyList[attr].url,
            changeOrigin : true ,
            secure: false,
            pathRewrite : !proxyList[attr].rewrite ? {
                    ["^"+attr] : ""
            } : {}
        };
        proxys[attr] = options;  
    }
}

function dealCopyPlugin(){
    plugins.push(
        new CopyWebPlugin(copyPlugin)
    );
}
init();

module.exports = {
    plugins,
    proxys
}